package com.ler.fast.util;

import com.ler.fast.entity.UserAccount;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;

/**
 * @author lww
 * @date 2020-07-14 09:55
 */
public class InjectUtil {

    public static UserAccount inject() {
        ApplicationContext context = SpringBeanFactoryUtils.getApplicationContext();
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getAutowireCapableBeanFactory();
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(UserAccount.class);
        builder.addPropertyValue("userName", "张三");
        beanFactory.registerBeanDefinition("userAccount", builder.getBeanDefinition());
        return context.getBean(UserAccount.class);
    }

    public static void destroy() {
        ApplicationContext context = SpringBeanFactoryUtils.getApplicationContext();
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getAutowireCapableBeanFactory();
        beanFactory.removeBeanDefinition("userAccount");
    }

}
